﻿using Common;
using Common.Enums;
using enterprise.Website.Core.Filter;
using FreeSql.Context;
using FreeSql.Model;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;


namespace enterprise.Website.Core.ApiControllers
{
    [Route("api/[controller]")]
    [ApiController]
    [LoginAuthorize]
    public class NewsInfoController : ControllerBase
    {
        private readonly SqlContext _sqlContext;
        private readonly ICache _cache;

        public NewsInfoController(SqlContext sqlContext, ICache cache)
        {
            _sqlContext = sqlContext;
            _cache = cache;
        }

        /// <summary>
        /// 获取新闻列表
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<PageModel<News_Info>> Get(int page = 1,int limit = 10)
        {
            long Count = 0;
            var list = await _sqlContext.DB.Select<News_Info, LanguageType,ContentClass>()
                .LeftJoin((t, t1,t2) => t.LanguageId == t1.Id)
                .LeftJoin((t, t1, t2) => t.ClassId == t2.Id)
                .Page(page, limit)
                .Count(out Count)
                .OrderByDescending((t, t1, t2) => t.Sort)
                .ToListAsync((t, t1 ,t2) => new News_Info
                {
                    Id = t.Id,
                    Title = t.Title,
                    ClassId=t.ClassId,
                    IsShow=t.IsShow,
                    Sort=t.Sort,
                    LanguageId=t.LanguageId,
                    NewsTime=t.NewsTime,
                    ClassName=t2.ClassName,
                    LanguageName=t1.Language
                });
            //计算总页数
            int pageCount = (Math.Ceiling(Count.ObjToDecimal() / limit.ObjToDecimal())).ObjToInt();
            return new PageModel<News_Info>
            {
                count = Count,
                data = list,
                PageSize = limit,
                PageCount = pageCount,
                PageIndex = page,
                code = Count == 0 ? -1 : 0,
                msg = Count == 0 ? "暂无数据" : ""
            };
        }

        /// <summary>
        /// 获取新闻内容
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public async Task<ApiResult<News_Info>> GetInfo(int id = 0)
        {
            var result = new ApiResult<News_Info> { Success = false, Message = "查询失败" };
            if (id > 0)
            {
                var resData = await _sqlContext.QueryInfoAsync<News_Info>(m => m.Id == id);
                if (resData != null)
                {
                    result.Data = resData;
                    result.Success = true;
                    result.Message = "查询成功";
                }
            }
            return result;
        }

        /// <summary>
        /// 发表新闻
        /// </summary>
        /// <param name="value"></param>
        [HttpPost]
        public async Task<ApiResult<int>> Post([FromBody] News_Info data)
        {
            var result = new ApiResult<int> { Success = false, Message = "保存失败" };
            if (data != null)
            {
                data.NewsTime = DateTime.Now.ToString();
                var ClassInfo = await _sqlContext.QueryInfoAsync<ContentClass>(m => m.Id == data.ClassId);
                if (ClassInfo == null)
                {
                    result.Message = "此栏目已不存在，请重新选择栏目";
                    return result;
                }
                if (ClassInfo.ClassType != (int)ClassType.News)
                {
                    result.Message = "新闻必须在新闻列表页栏目下，请选择新闻列表页类型的栏目";
                    return result;
                }
                var Id = await _sqlContext.AddAsync(data);
                if (Id > 0)
                {
                    result.Data = Id.ObjToInt();
                    result.Success = true;
                    result.Message = "保存成功";
                    _cache.Remove($"{SystemConstConfig.News}_{data.LanguageId}");
                }
            }
            return result;
        }

        /// <summary>
        /// 编辑新闻
        /// </summary>
        /// <param name="id"></param>
        /// <param name="value"></param>
        [HttpPut("{id}")]
        public async Task<ApiResult> Put(int id, [FromBody] News_Info data)
        {
            var result = new ApiResult { Success = false, Message = "保存失败" };
            if (id > 0 && data != null)
            {
                data.Id = id;
                var ClassInfo = await _sqlContext.QueryInfoAsync<ContentClass>(m => m.Id == data.ClassId);
                if (ClassInfo == null)
                {
                    result.Message = "此栏目已不存在，请重新选择栏目";
                    return result;
                }
                if (ClassInfo.ClassType != (int)ClassType.News)
                {
                    result.Message = "新闻必须在新闻列表页栏目下，请选择新闻列表页类型的栏目";
                    return result;
                }
                var Count = await _sqlContext.UpdateAsync<News_Info>(m=>new News_Info 
                {
                    LanguageId=data.LanguageId,
                    SeoDescription=data.SeoDescription,
                    ClassId=data.ClassId,
                    SeoKeywords=data.SeoKeywords,
                    Sort=data.Sort,
                    IsShow=data.IsShow,
                    ClassName=data.ClassName,
                    Content=data.Content,
                    Title=data.Title,
                    TitleImg=data.TitleImg
                },n=>n.Id==id);
                if (Count > 0)
                {
                    result.Success = true;
                    result.Message = "保存成功";
                    _cache.Remove($"{SystemConstConfig.News}_{data.LanguageId}");
                }
            }
            return result;
        }

        /// <summary>
        /// 删除新闻
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete("{id}")]
        public async Task<ApiResult> Delete(int id)
        {
            var result = new ApiResult { Success = false, Message = "删除失败" };
            if (id > 0)
            {
                var newsInfo = await _sqlContext.QueryInfoAsync<News_Info>(m => m.Id == id);
                if (newsInfo != null)
                {
                    var Count = await _sqlContext.DeleteAsync<News_Info>(m => m.Id == id);
                    if (Count > 0)
                    {
                        result.Success = true;
                        result.Message = "删除成功";
                        _cache.Remove($"{SystemConstConfig.News}_{newsInfo.LanguageId}");
                    }
                }
            }
            return result;
        }
    }
}
